<?php
/**
*
*
*/
abstract class Yz_Application_Web
    extends Yz_Application_Abstract
{

    /**
     * @var Yz_Router_Interface&
     */
    protected static $router;


    /** Main entry method
     *      Add output buffering
     *  @return int
     */
    public static function main($args=null)
    {
        ob_start();
        static::init();
        $rq = static::initRequest();
        $rs = static::initResponse();
        $rs = static::selectRouter()
            ->routeRequest($rq, $rs)
        ;
        assert('$rs instanceof Yz_HTTP_Response_Interface');
        return static::sendResponse($rs);
    }

    /** select router application-wide and store it for possible access
     *  @return Yz_Router_Interface
     */
    public static function selectRouter()
    {
        $router =& self::$router;
        if (! $router) {
            $class = Yz::loadClassNS('Router_Default');
            #assert('is_subclass_of($class,"Yz_Router_Interface")');
            $router = $class::getInstance();
        }
        return $router;
    }

    /** A separate method to allow subclasses to hook
     *  @return int
     */
    protected static function sendResponse( Yz_HTTP_Response_Interface $rs )
    {
        $rs->send();
        return 0;
    }

    /** initialize HTTP Request object
     *  @return Yz_HTTP_Request_Interface
     */
    protected static function initRequest()
    {
        return Yz_HTTP_Request::getInstance();
    }

    /** initialize HTTP Response object
     *  @return Yz_HTTP_Response_Interface
     */
    protected static function initResponse()
    {
        return Yz_HTTP_Response::getInstance();
    }


    /**
     *  @return void
     */
    protected static function displayErrorMessage( $message )
    {
        // dispose of any buffered data
        while ( false !== ob_get_length() )
            ob_end_clean();

        // ensure the message appears regardless of the status
        // of Response objects and current directory
        header_remove(); // remove all headers
        header( 'HTTP/1.1 500 Internal Server Error' );
        header( 'Content-Type: text/html; charset=utf-8' );
        header( 'Cache-Control: no-cache' );
        header( 'Last-Modified: ' . gmdate( 'r', YZ_TIME ) );
        header( 'Expires: Mon, 26 Jul 1997 05:00:00 GMT' );
        include( YZ_LIB . 'Yz/templates/fatal-error.php' );
    }


} // class


